package com.jeecg.p3.system.web.app;


import com.jeecg.p3.base.util.ComCode;
import com.jeecg.p3.base.util.StringUtils;
import com.jeecg.p3.base.util.WxUserInfo;
import com.jeecg.p3.base.util.WxUtils;
import com.jeecg.p3.system.base.BaseController;
import com.jeecg.p3.system.entity.Product;
import com.jeecg.p3.system.order.entity.ProductDetails;
import com.jeecg.p3.system.order.service.ProductDetailsService;
import com.jeecg.p3.system.poster.entity.CustomerCoupon;
import com.jeecg.p3.system.poster.service.CustomerCouponService;
import com.jeecg.p3.system.service.ProductService;
import com.jeecg.p3.system.util.Constants;
import org.apache.velocity.VelocityContext;
import org.jeecgframework.p3.core.common.utils.AjaxJson;
import org.jeecgframework.p3.core.util.SystemTools;
import org.jeecgframework.p3.core.util.plugin.ViewVelocity;
import org.jeecgframework.p3.core.utils.common.PageQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * 手机端主页相关接口
 */
@Controller
@RequestMapping("/app/personCenter")
public class PersonCenterController extends BaseController {

    @Autowired
    private CustomerCouponService service;
    @Autowired
    private ProductDetailsService productDetailsService;
    @Autowired
    private ProductService productService;

    /**
     * 跳转到个人主页
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "/main", method = { RequestMethod.GET, RequestMethod.POST })
    public void index(HttpServletRequest request,
                      HttpServletResponse response) throws Exception
    {
        log.info("------跳转到微信个人主页开始------");
        VelocityContext velocityContext = new VelocityContext();
        WxUserInfo wxUserInfo = getWxUserInfo(request);
        String toUrl = ComCode.systemUrl + "/app/personCenter/main.do";
        if(wxUserInfo == null || StringUtils.isEmpty(wxUserInfo.getOpenid())) {
            AjaxJson j = WxUtils.getWxUserDetail(request);
            if(j.isSuccess()) {
                wxUserInfo = (WxUserInfo) j.getObj();
                request.getSession().setAttribute(Constants.wxInfo, j.getObj());
            } else {
                String url = ComCode.authorize + "appid=" + ComCode.appid + "&redirect_uri="
                        + URLEncoder.encode(toUrl, "UTF-8") + ComCode.userinfoUrl;
                response.sendRedirect(url);
                return;
            }
        }
        /*String code = request.getParameter("code");
        if(StringUtils.isNotEmpty(code)) {
            log.info("------检测到有code进行再次跳转！！！");
            response.sendRedirect(toUrl);
            return;
        }*/
        log.info("openId : " + wxUserInfo.getOpenid());
        String viewName = "system/back/app/personCenter.html";//跳转到H5授权界面
        velocityContext.put("userInfo", wxUserInfo);
        log.info("------跳转到微信个人主页结束------");
        ViewVelocity.view(request, response, viewName, velocityContext);
    }

    /**
     * 查询自己的优惠券
     * @param query
     * @param request
     * @param response
     * @param pageNo
     * @param pageSize
     * @throws Exception
     */
    @RequestMapping(value="/myCoupon",method = {RequestMethod.GET,RequestMethod.POST})
    public void myCoupon(@ModelAttribute CustomerCoupon query, HttpServletRequest request, HttpServletResponse response,
                              @RequestParam(required = false, value = "pageNo", defaultValue = "1") int pageNo,
                              @RequestParam(required = false, value = "pageSize", defaultValue = "10") int pageSize) throws Exception{

        log.info("------查询我的课程优惠券开始------");
        WxUserInfo wxUserInfo = getWxUserInfo(request);
        String toUrl = ComCode.systemUrl + "/app/personCenter/myCoupon.do";
        if(wxUserInfo == null || StringUtils.isEmpty(wxUserInfo.getOpenid())) {
            AjaxJson j = WxUtils.getWxUserDetail(request);
            if(j.isSuccess()) {
                wxUserInfo = (WxUserInfo) j.getObj();
                request.getSession().setAttribute(Constants.wxInfo, j.getObj());
            } else {
                String url = ComCode.authorize + "appid=" + ComCode.appid + "&redirect_uri="
                        + URLEncoder.encode(toUrl, "UTF-8") + ComCode.userinfoUrl;
                response.sendRedirect(url);
                return;
            }
        }
        /*String code = request.getParameter("code");
        if(StringUtils.isNotEmpty(code)) {
            log.info("------检测到有code进行再次跳转！！！");
            response.sendRedirect(toUrl);
            return;
        }*/
        PageQuery<CustomerCoupon> pageQuery = new PageQuery<>();
        pageQuery.setPageNo(pageNo);
        pageQuery.setPageSize(pageSize);
        VelocityContext velocityContext = new VelocityContext();
        String viewName = "system/back/app/coupon_list.html";
        query.setUseStatus("0");
        query.setWxOpenId(wxUserInfo.getOpenid());
        pageQuery.setQuery(query);
        velocityContext.put("pageInfos", SystemTools.convertPaginatedList(service.queryPageList(pageQuery)));
        log.info("------查询我的课程优惠券结束------");
        ViewVelocity.view(request,response,viewName,velocityContext);
    }

    /**
     * 查询我的课程信息
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value="/myProduct",method = {RequestMethod.GET,RequestMethod.POST})
    public void myProduct(HttpServletRequest request, HttpServletResponse response) throws Exception{
        log.info("------查询我的课程信息开始------");
        WxUserInfo wxUserInfo = getWxUserInfo(request);
        String toUrl = ComCode.systemUrl + "/app/personCenter/myProduct.do";
        if(wxUserInfo == null || StringUtils.isEmpty(wxUserInfo.getOpenid())) {
            AjaxJson j = WxUtils.getWxUserDetail(request);
            if(j.isSuccess()) {
                wxUserInfo = (WxUserInfo) j.getObj();
                request.getSession().setAttribute(Constants.wxInfo, j.getObj());
            } else {
                String url = ComCode.authorize + "appid=" + ComCode.appid + "&redirect_uri="
                        + URLEncoder.encode(toUrl, "UTF-8") + ComCode.userinfoUrl;
                response.sendRedirect(url);
                return;
            }
        }
        /*String code = request.getParameter("code");
        if(StringUtils.isNotEmpty(code)) {
            log.info("------检测到有code进行再次跳转！！！");
            response.sendRedirect(toUrl);
            return;
        }*/

        VelocityContext velocityContext = new VelocityContext();
        String viewName = "system/back/app/product_list.html";
        ProductDetails param = new ProductDetails();
        param.setOpenId(wxUserInfo.getOpenid());
        param.setUserStatus(1);
        List<ProductDetails> productDetailsList = productDetailsService.findByParamGroupBy(param);
        List<Product> products = new ArrayList<>();
        for(ProductDetails p: productDetailsList) {
            if(p != null && StringUtils.isNotEmpty(p.getProductId())) {
                Product product = productService.queryById(Long.valueOf(p.getProductId()));
                if(product != null) {
                    products.add(product);
                }
            }
        }
        velocityContext.put("pageInfos", products);
        ViewVelocity.view(request,response,viewName,velocityContext);
    }
}
